<script setup>
import {onMounted, ref, watch} from "vue";
import VInput from "./VInput.vue";

const props = defineProps({
  modelValue: {
    type: [String, Number, Boolean, Array],
    default: ''
  },
  options: {
    type: Array,
    default: () => {
      return [];
    }
  },
  label: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  },
  style: {
    type: Object,
    default: () => {
      return {
        width: '100%'
      };
    }
  }
});
const emits = defineEmits(['update:modelValue', 'input', 'change']);
// 绑定数据
const inputValue = ref(props.modelValue);
const placeholderValue = ref(props.placeholder);
// 监听父组件中传递的数据是否发生变化
watch(() => props.modelValue, (val) => {
  inputValue.value = val;
}, {deep: true});
// 监听当前组件中的输入框数据是否发生变化，变化则需要通知父组件更新数据
watch(() => inputValue.value, (val) => {
  inputValue.value = val;
  handleEmits();
}, {deep: true});

onMounted(() => {
  placeholderValue.value = props.placeholder ? props.placeholder : '请输入' + props.label;
});
const handleEmits = (type) => {
  emits('update:modelValue', inputValue.value);
  if (type === 'input') {
    emits('input', inputValue.value);
  } else if (type === 'change') {
    emits('change', inputValue.value);
  }
};
</script>

<template>
  <el-form-item class="v-form-item" :label="label" :label-width="width">
    <v-input v-model="inputValue" :options="options" :placeholder="placeholderValue" v-bind="$attrs"
             :style="style" @input="handleEmits('input')" @change="handleEmits('change')"/>
  </el-form-item>
</template>

<style scoped>
.v-form-item :deep(.el-input__wrapper), :deep(.el-textarea__inner), :deep(.el-checkbox__inner) {
  border-radius: 0;
}
</style>